<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert show-icon title="注意：只允许为三级分类设置相关参数！" type="warning"></el-alert>
      <div class="block" style="margin-top: 15px;">选择商品分类：
        <!-- props指定配置对象 -->
        <el-cascader clearable :props="cascaderProps" v-model="selectedOption" :options="cateList" @change="handleChange"></el-cascader>
      </div>
      <el-tabs style="margin-top: 15px;" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button @click="showDialog" style="margin-bottom: 15px;" type="primary" size="mini" :disabled="isBtnDisabled">添加参数</el-button>
          <el-table stripe border :data="manyTableData" style="width: 100%">
            <el-table-column  type="expand">
              <template slot-scope="scope">
                <el-tag closable @close="handleClose(i, scope.row)" type="success" v-for="(item,i) in scope.row.attr_vals" :key="i">{{ item }}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column  type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column prop="operation" label="操作">
              <template slot-scope="scope">``
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" @click="deleteWarning(scope.row.attr_id)" icon="el-icon-delete" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button @click="showDialog" style="margin-bottom: 15px;" type="primary" size="mini" :disabled="isBtnDisabled">添加属性</el-button>
            <el-table stripe border :data="onlyTableData" style="width: 100%">
            <el-table-column  type="expand">
              <template slot-scope="scope">
                <el-tag closable @close="handleClose(i, scope.row)" type="success" v-for="(item,i) in scope.row.attr_vals" :key="i">{{ item }}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column  type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column prop="operation" label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" @click="deleteWarning(scope.row.attr_id)" icon="el-icon-delete" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog @close="addDialogClose" :title="'添加'+titleText" :visible.sync="dialogVisible" width="50%">
      <el-form ref="addFormRef" :rules="addFormRules" :model="addForm" label-width="110px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
        <el-dialog @close="editDialogClose" :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%">
      <el-form ref="editFormRef" :rules="editFormRules" :model="editForm" label-width="110px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getCategories()
  },
  data () {
    return {
      attrId: '',
      dialogVisible: false,
      paramList: [],
      activeName: 'many',
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      selectedOption: [],
      cateList: [],
      selectedId: [],
      manyTableData: [],
      onlyTableData: [],
      editDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      requestBody: {
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      }
    }
  },
  computed: {
    isBtnDisabled () {
      return this.selectedOption.length !== 3
    },
    getSelectId () {
      if (this.selectedOption.length !== 3) {
        return null
      }
      return this.selectedOption[2]
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  methods: {
    async deleteWarning (id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 确定返回confirm 否则返回cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('您已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.selectedOption[2]}/attributes/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.info(res.meta.msg)
      this.getParams()
    },
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    showDialog () {
      this.dialogVisible = true
    },
    async showEditDialog (attrId) {
      this.attrId = attrId
      const { data: res } = await this.$http.get(`/categories/${this.selectedOption[2]}/attributes/${attrId}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    async getCategories () {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
      console.log(this.cateList)
    },
    async getParams () {
      const { data: res } = await this.$http.get(`/categories/${this.selectedOption[2]}/attributes`, { params: { sel: this.activeName } })
      if (this.selectedOption.length !== 3) {
        this.selectedOption = []
        this.manyTableData = []
        this.onlyTableData = []
      }
      // if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 将attr_value字符串形式转化为数组形式
      res.data.forEach(item => {
        if (item.attr_vals === '') {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(',')
        }
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      console.log(res)
    },
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.selectedOption[2]}/attributes/${this.attrId}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        console.log(res)
        this.getParams()
        this.editDialogVisible = false
      })
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        // 自动获得焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      // 自动恢复成按钮
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    async saveAttrVals (row) {
      this.requestBody.attr_name = row.attr_name
      this.requestBody.attr_sel = row.attr_sel
      this.requestBody.attr_vals = row.attr_vals.join(',')
      const { data: res } = await this.$http.put(`categories/${this.selectedOption[2]}/attributes/${row.attr_id}`, this.requestBody)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('修改参数项成功')
    },
    handleChange () {
      console.log(this.selectedOption)
      this.getParams()
    },
    handleClick () {
      console.log(this.activeName)
      this.getParams()
    },
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.selectedOption[2]}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        console.log(res)
        this.getParams()
        this.dialogVisible = false
      })
    },
    // 删除参数可选项
    handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  }
}
</script>

<style lang='less' scoped>
.el-tag {
  margin: 5px
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
